package com.zn.websocket.server;

import com.zn.websocket.init.HttpInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.ResourceLeakDetector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * webSocket启动类
 * yinjiawei
 */
@Component
public class WebSocketServer {

    @Autowired
    HttpInitializer httpInitializer;

    private final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    public void run(int port) throws InterruptedException {
        EventLoopGroup bossGroup = Epoll.isAvailable() ? new EpollEventLoopGroup(2) : new NioEventLoopGroup(2);
        EventLoopGroup workerGroup = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class);

        bootstrap.childHandler(httpInitializer);
        ChannelFuture channelFuture = bootstrap.bind(port).sync();
        Channel channel = channelFuture.channel();
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
        channel.closeFuture().sync();
    }

    public static void main(String[] args) throws InterruptedException {
        new WebSocketServer().run(80);
    }

}
